<?php
/**
 * 说明.
 * User: dxk <1024114660@qq.com>
 * Date: 2024/3/9
 */
namespace App\Library\Service\AliCloud;

use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class STS
{
    /**
     * 使用AK&SK初始化账号Client
     * @return \AlibabaCloud\SDK\Sts\V20150401\Sts Client
     */
    public static function createClient(): \AlibabaCloud\SDK\Sts\V20150401\Sts
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => config('sys.aliyun.accessKeyId'),
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => config('sys.aliyun.accessSecret')
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Sts
        $config->endpoint = config('sys.aliyun.sts_endpoint');
        return new \AlibabaCloud\SDK\Sts\V20150401\Sts($config);
    }

    /**
     * 生成临时凭证
     * @param string $role_session_name
     * @return array
     */
    public static function assumeRole(string $role_session_name): array
    {
        $params = [
            "durationSeconds" => 900,
            "roleArn" => config('sys.aliyun.sts_oss_role_arn'),
            "roleSessionName" => $role_session_name
        ];
        $assumeRoleRequest = new AssumeRoleRequest($params);
        $runtime = new RuntimeOptions([]);
        $client = self::createClient();
        try {
            $response = $client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
            easy_log('alicloud/sts', ['action' => 'assumeRole', 'options' => $params, 'res' => $response]);
            $response = json_decode(json_encode($response, JSON_UNESCAPED_UNICODE), true);
            if ($response['statusCode'] != 200) {
                return alert_info(1, '请求失败');
            } else {
                return alert_info(0, "", $response['body']);
            }
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return alert_info(1, $error->message);
        }
    }
}
